/**
* 树结构数组扁平化
* @param {*} data 树结构的数组
* @returns
*/
export function treeToArray(data: any[], pid: string|number): any[] {
  return data.reduce((pre, cur) => {
    const { children = [], ...item } = cur;
    return pre.concat([{ ...item, pid }], treeToArray(children, item.id))
  }, []);
}

/**
 * 一维数组转树结构
 * @param items
 * @returns
 */

export function arrayToTree(items: any[]) {
  const result = [];   // 存放结果集
  const itemMap: any = {};  //
  for (const item of items) {
    const id = item.id;
    const pid = item.pid;

    if (!itemMap[id]) {
      itemMap[id] = {
        children: [],
      }
    }

    itemMap[id] = {
      ...item,
      children: itemMap[id]['children']
    }

    const treeItem = itemMap[id];

    if (pid === '0') {
      result.push(treeItem);
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = {
          children: [],
        }
      }
      itemMap[pid].children.push(treeItem)
    }

  }
  return result;
}

// export const findItem = function(list:any[],key:string,value:any){
//   return R.find(R.propEq(key, value))(list)
// }

// export const mapListSetValueBymap = (list:any[],key:string,obj:object)=> {
//   return R.map((item)=> R.assoc(key,R.pathOr('',[item.prop], obj),item), list)
// }

// export const mapListDelKey = (list:any[],key:string)=> {
//   list = R.map(R.dissoc(key), list)
// }

export const listItemAddKey = function(list:any){
  return list.map((v:any)=>({...v,label:v.simple_name ?? v.name,value:v.id,children: v.children ? listItemAddKey(v.children):null}))
}

export const listItemAddKeycolumnName = function(list:any){
  return list.map((v:any)=>({...v,label:v.column_name,value:v.column_name,children: v.children ? listItemAddKeycolumnName(v.children):null}))
}


export const move = (f:number, t:number, list:any[])=> {
  const from = f - 1;
  const to = t - 1;
  const length = list.length;
  const result = list.slice();
  const positiveFrom = from < 0 ? length + from : from;
  const positiveTo = to < 0 ? length + to : to;
  const item = result.splice(positiveFrom, 1);
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  return positiveFrom < 0 || positiveFrom >= list.length || positiveTo < 0 || positiveTo >= list.length ? list : [].concat(result.slice(0, positiveTo)).concat(item).concat(result.slice(positiveTo, list.length));
}
